package com.nut.service.product;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.github.pagehelper.PageHelper;
import com.nut.dao.ProductMapper;
import com.nut.pojo.ProductExample;
import com.nut.pojo.ProductQuery;
import com.nut.pojo.ProductWithBLOBs;
import com.nut.pojo.Sku;
import com.nut.service.sku.SkuServiceI;

/**
 * @author Nut
 * @version 2018年8月11日 下午2:34:57
 * @TODO
 *
 */
@Service
public class ProductServiceImpl implements ProductServiceI {

	@Resource
	ProductMapper pm;
	@Resource
	SkuServiceI skuService;

	/*
	 * 在生成商品时，则在数据库中加入对应的sku 获取生成product对象在向数据库添加后，自增长的id
	 * 在ProductMapper.xml文件中加以下代码      useGeneratedKeys="true" keyProperty="id"
	 * <insert id="insertSelective"
	 * parameterType="com.nut.pojo.ProductWithBLOBs" useGeneratedKeys="true"
	 * keyProperty="id"> 
	 * 
	 * 开启spring注解驱动
	 * 1、配置tx.xml文件
	 * 2、在service项目中pom.xml中添加 spring-orm的依赖
	 * 3、在所需的方法上添加注解 @Transactional
	 */
	@Override
	@Transactional
	public int add(ProductWithBLOBs product) {
		int result = 0;
		result += pm.insertSelective(product);
		String[] storages = product.getStorageList().split(",");
		String[] colors = product.getColorList().split(",");
		for (String color : colors) {
			for (String storage : storages) {
				Sku sku = new Sku();
				sku.setColorId(Integer.parseInt(color));
				sku.setStorageId(Integer.parseInt(storage));
				sku.setPrice(product.getPrice());
				sku.setSales(0);
				sku.setSort(1);
				sku.setStock(0);
				sku.setProductId(product.getId());
				result += skuService.add(sku);
			}
		}
		return result;

		// return pm.insertSelective(product);
	}

	@Override
	public List<ProductWithBLOBs> queryByPages(ProductWithBLOBs product, ProductExample example) {
		if (product.getWithPage() == 1) {
			PageHelper.startPage(product.getPageNo(), product.getPageSize());
		}
		return pm.selectByExampleWithBLOBs(example);
	}

	@Override
	public int delete(ProductWithBLOBs product) {
		product.setIsDel(0);
		return pm.updateByPrimaryKeySelective(product);
	}

	@Override
	public ProductWithBLOBs queryOne(int id) {

		return pm.selectByPrimaryKey(id);
	}

	@Override
	public int update(ProductWithBLOBs product) {

		return pm.updateByPrimaryKeySelective(product);
	}
	
	/*
	 * 前端多条件查询，
	 * 无条件时则显示全部商品
	 * 此处可进行分页显示
	 * in:
	 * out:
	 */
	@Override
	public List<ProductWithBLOBs> search(ProductQuery productQuery) {
		if(productQuery.getWithPage()==1)
			PageHelper.startPage(productQuery.getPageNo(), productQuery.pageSize);
		return pm.search(productQuery);
	}


}
